package com.ruoyi.business.youdaoController.shangyou;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.services.HttpService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * WIFI->小红书
 */
@RestController
@RequestMapping("ownWfToXhsApi")
public class WFToXHSController {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private HttpService httpService;
    @Autowired
    private IDynamicSearchService dynamicSearchService;

    private final static String CLASSESEN = "youdao";


    //wifi回调地址
    private final static String CALLBACK_URLBASE = "http://c2.wkanx.com/tracking";



    /**
     * https://www.ssptqt.com/ownWfToXhsApi/send?channelId=6954840741332992&dmpid=__SID__&cid=__CID__&idfa=__PLAIN_IDFA__&idfa_md5=__IDFA__&imeimd5=__IMEI__&oaid=__OAID__&imei=__PLAIN_IMEI__&mac=__MAC__&timestamp=__STIME__&os=__OS__&ip=&ua=
     * wifi->小红书
     * @param request
     * @return
     * @throws Exception
     */
    @Log(title = "有道", businessType = BusinessType.ESCALATION, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);

        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);


        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            //request 获取 ua
            ua = request.getHeader("User-Agent");
            baseParamsMap.put("ua", URLEncoder.encode(ua, Constants.UTF8));
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            //request 获取 ip
            ip = IpUtils.getIpAddr(request);
            baseParamsMap.put("ip", ip);
        }

        String callbackClientId = channelDetail.get("callback_clientid") + "";
        String callbackSecretkey = channelDetail.get("callback_secretkey") + "";

        String os = getMapValue(baseParamsMap, "os");

        LinkedHashMap<String, String> callbackMap = new LinkedHashMap<>();
        callbackMap.put("cid", getMapValue(baseParamsMap, "cid"));
        callbackMap.put("clientid", callbackClientId);
        callbackMap.put("clientkey", callbackSecretkey);
        callbackMap.put("idfa", getMapValue(baseParamsMap, "idfa_md5"));
        callbackMap.put("imei", getMapValue(baseParamsMap, "imeimd5"));
        //下游的mac是进行MD5加密过的就是上游的mac_md5
        callbackMap.put("mac", getMapValue(baseParamsMap, "mac"));
        callbackMap.put("os", os);
        //sid代表请求标识
        callbackMap.put("sid", dmpid);
        //stime为上报时间戳。 上传过来的参数为ts
        callbackMap.put("stime", getMapValue(baseParamsMap, "timestamp"));

        List<String> tempList = new ArrayList<>();
        for(String key: callbackMap.keySet()){
            tempList.add(key+"="+callbackMap.get(key));
        }
        String callbackParams = String.join("&", tempList);
        EncrypDES encrypDES = new EncrypDES();
        String callbackBase = OtherUtils.getServerUrl(request) + "ownWfToXhsApi/callback/"+channelId+"/"+dmpid+"/";
        String encrypt_u = encrypDES.encrypt(CALLBACK_URLBASE);
        String nu = callbackBase + encrypt_u + "?"+callbackParams;
        //nu 必须以https开头
        nu = nu.replace("http://", "https://");


        baseParamsMap.put("os", os.equals("0")?"ANDROID":os.equals("1")?"IOS":"OTHERS");
        baseParamsMap.put("ts", baseParamsMap.get("timestamp"));
        baseParamsMap.put("callback_url", URLEncoder.encode(nu, Constants.UTF8));

        //https://www.xiaohongshu.com/api/sns/v1/ext/ads/CPA-3DSP-N0-{代理商标识}/clk_collect?
        // ts_sec=__ACTION_TIME__&callback_url=__CALLBACK__&platform=ANDROID&imei_sum=__IMEI_MD5__&oaid=__OAID__&oaid_sum=__OAID_MD5__&mac=__MAC__&ip=__IP__&ua=__UA__

        //oaid和oaid_sum， 如果oaid不为空，并且oaid_sum为空，则添加oaid_sum字段。 oaid的md5值
        String oaid = baseParamsMap.get("oaid") + "";
        if(StringUtils.isNotBlank(oaid) && !"null".equals(oaid)){
            String oaidSumStr = DigestUtils.md5DigestAsHex(oaid.getBytes());
            baseParamsMap.put("oaid_sum", oaidSumStr);
        }

        String imei = baseParamsMap.get("imei") + "";
        String imeimd5 = baseParamsMap.get("imeimd5") + "";
        //如果imei为__PLAIN_IMEI__, 则判断imeimd5是否为控，如果不为空则讲imeimd5的值赋给imei
        if(("__PLAIN_IMEI__".equals(imei) || StringUtils.isBlank(imei)) && StringUtils.isNotBlank(imeimd5) && !"null".equals(imeimd5) && !"__IMEI__".equals(imeimd5)){
            //imeimd5 小写
            baseParamsMap.put("imei", imeimd5.toLowerCase());
        }

        //如果idfa为__PLAIN_IDFA__, 则判断idfa_md5是否为控，如果不为空则讲idfa_md5的值赋给idfa
        String idfa = baseParamsMap.get("idfa") + "";
        String idfaMd5 = baseParamsMap.get("idfa_md5") + "";
        if("__PLAIN_IDFA__".equals(idfa) && StringUtils.isNotBlank(idfaMd5) && !"null".equals(idfaMd5) && !"__IDFA__".equals(idfaMd5)){
            baseParamsMap.put("idfa", idfaMd5);
        }



        Map<String, Object> baseParamsMapTemp = new HashMap<>();
        baseParamsMapTemp.put("ts_sec", baseParamsMap.get("ts"));
        baseParamsMapTemp.put("platform", baseParamsMap.get("os"));
        baseParamsMapTemp.put("imei_sum", baseParamsMap.get("imeimd5"));
        baseParamsMapTemp.put("oaid", baseParamsMap.get("oaid"));
        baseParamsMapTemp.put("oaid_sum", baseParamsMap.get("oaid_sum"));
        baseParamsMapTemp.put("mac", baseParamsMap.get("mac"));
        baseParamsMapTemp.put("idfa", baseParamsMap.get("idfa"));
        baseParamsMapTemp.put("idfa_sum", baseParamsMap.get("idfa_md5"));
//        baseParamsMapTemp.put("caid0", baseParamsMap.get("cid"));
//        baseParamsMapTemp.put("caid1", baseParamsMap.get("cid"));
        baseParamsMapTemp.put("ip", baseParamsMap.get("ip"));
        baseParamsMapTemp.put("ua", baseParamsMap.get("ua"));
        baseParamsMapTemp.put("callback_url", baseParamsMap.get("callback_url"));
        baseParamsMapTemp.put("media_name", "wifiwannengyaoshi");


        tempList = new ArrayList<>();
        for(String key: baseParamsMapTemp.keySet()){
            String value = baseParamsMapTemp.get(key) + "";
            if(value.startsWith("__") && value.endsWith("__")){
                value = "";
            }
            if(StringUtils.isBlank(value) || "null".equals(value)){
                value = "";
            }
            tempList.add(key+"="+value);
        }
        String requestParameters = String.join("&", tempList);

        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "click";
        if("POST".equals(requestType)){
            httpService.sendPost(requestAddress, requestParameters, null, ua, uuid, reqType);
        }else{
            httpService.sendGet(requestAddress, requestParameters, null, ua, uuid, reqType);
        }
        return R.success().msg(uuid);
    }


    @Log(title = "有道", businessType = BusinessType.CALLBACK, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/callback/{channelId}/{dmpid}/{encryptedUrl}")
    public Object callback(HttpServletRequest request, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        String queryString = request.getQueryString();
        Map<String, Object> queryMap = GetUrlParam.queryStrToMap(queryString);
        String eventType = queryMap.get("conv_type") + "";
        if("ACTIVATE_APP".equals(eventType)){
            queryMap.put("event_type", 1);
        }else if("REGISTER".equals(eventType)) {
            queryMap.put("event_type", 2);
        }else if("RETENTION".equals(eventType)){
            queryMap.put("event_type", 5);
        }else {
            queryMap.put("event_type", 1);
        }


        LinkedHashMap<String, String> callbackMap = new LinkedHashMap<>();
        callbackMap.put("cid", getMapValue(queryMap, "cid"));
        callbackMap.put("clientid", getMapValue(queryMap, "clientid"));

        callbackMap.put("idfa", getMapValue(queryMap, "idfa"));
        //下游没有imei, 但是有imei_md5
        callbackMap.put("imei", getMapValue(queryMap, "imei"));
        //下游的mac是进行MD5加密过的就是上游的mac_md5
        callbackMap.put("mac", getMapValue(queryMap, "mac"));
        callbackMap.put("os", getMapValue(queryMap, "os"));
        //sid是下游给的click_id。 代表请求标识
        callbackMap.put("sid", getMapValue(queryMap, "sid"));
        //stime为上报时间戳。 上传过来的参数为ts
        callbackMap.put("stime", getMapValue(queryMap, "stime"));
        //获取当前时间戳 并转化为秒
        callbackMap.put("ts", (System.currentTimeMillis()/1000)+"");

        String callbackSecretkey = getMapValue(queryMap, "clientkey");
        List<String> tempList = new ArrayList<>();
        for(String key: callbackMap.keySet()){
            tempList.add(key+"="+callbackMap.get(key));
        }
        String callbackParams = String.join("&", tempList);
        String md5 = DigestUtils.md5DigestAsHex((callbackParams+callbackSecretkey).getBytes(Constants.UTF8)).toUpperCase();
        callbackParams = callbackParams + "&event_type="+getMapValue(queryMap, "event_type");
        queryString = callbackParams + "&sign="+md5;

        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);

        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "callback";
        httpService.sendGet(requestAddress, queryString, null, null, uuid, reqType);
        return R.success();
    }


    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }

}
